package com.simulation.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.simulation.common.dto.CodeWorkspaceDTO;
import com.simulation.common.exception.UtilException;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author zhangxn
 * @date 2024/12/11  23:42
 */
@Slf4j
public class CoderUtils {

    private static String ADD_USERS = "https://coder.yanzhiwei.top:31443/api/v2/users";


    private static String ADD_WORKSPACE = "https://coder.yanzhiwei.top:31443/api/v2/users/{}/workspaces";


    private static String LOGIN = "https://coder.yanzhiwei.top:31443/api/v2/users/login";

    private static String START_WORKSPACE = "https://coder.yanzhiwei.top:31443/api/v2/workspaces/{}/builds";

    private static String STATUS_WORKSPACE = "https://coder.yanzhiwei.top:31443/api/v2/users/{}/workspace/{}";

    private static String DELETE_WORKSPACE = "https://coder.yanzhiwei.top:31443/api/v2/workspaces/{}/builds";


    /**
     * 添加人员
     * @param userName
     * @param password
     * @param email
     */
    public static String addUser(String userName, String password,String email){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("email", email);
        jsonObject.put("name", userName);
        jsonObject.put("username", userName);
        jsonObject.put("user_status", "active");
        jsonObject.put("organization_ids","00000000-0000-0000-0000-000000000000".split(","));
        jsonObject.put("password", password);
        //链式构建请求
        String result2 = HttpRequest.post(ADD_USERS)
                .header("Coder-Session-Token", "FPcA7S0rcH-Xy1yBG9LaY7zMPdj8IB6da")//头信息，多个头信息多次调用此方法即可
                .body(jsonObject.toJSONString())//表单内容
                .timeout(20000)//超时，毫秒
                .execute().body();
        log.info("添加用户返回：{}", result2);
        JSONObject jsonObject1 = JSONObject.parseObject(result2);
        return jsonObject1.getString("id");
        // {"id":"d15ed23a-f02a-413f-9640-d1d0e6e514fc","username":"zxnapi1212","avatar_url":"","name":"zxnapi1212","email":"zxnapi1212@example.com","created_at":"2024-12-11T16:20:12.863984Z","updated_at":"2024-12-11T16:20:12.863987Z","last_seen_at":"0001-01-01T00:00:00Z","status":"active","login_type":"password","theme_preference":"","organization_ids":["66e8a45c-fdab-4118-99eb-ace95a7a2be0"],"roles":[]}
    }

    /**
     * 添加工作空间
     * @param userName
     * @param userId
     * @param gitRepo
     */
    public static String addWorkspace(String userName,String gitRepo,String userId){
        String url = StrUtil.format(ADD_WORKSPACE, userId);
        // old  c7304912-31a8-44b5-a45f-b9c76e748d0e
        String str = "{\"name\": \""+userName +"\",\"rich_parameter_values\":[{\"name\":\"environment\",\"value\":\"base\"},{\"name\":\"cpu\",\"value\":\"2\"},{\"name\":\"memory\",\"value\":\"2\"},{\"name\":\"git_branch\",\"value\":\"main\"},{\"name\":\"git_repo\",\"value\":\""+gitRepo+"\"},{\"name\":\"enable_code_server\",\"value\":\"true\"},{\"name\":\"enable_filebrowser\",\"value\":\"false\"},{\"name\":\"enable_kasmvnc\",\"value\":\"false\"},{\"name\":\"enable_terminal\",\"value\":\"true\"},{\"name\":\"enable_vscode_desktop\",\"value\":\"true\"}],\"template_version_id\":\"cc4a84c4-76f3-425a-9b34-8de1ad3a5b12\"}";
        //链式构建请求
        String result2 = HttpRequest.post(url)
                .header("Coder-Session-Token", "FPcA7S0rcH-Xy1yBG9LaY7zMPdj8IB6da")//头信息，多个头信息多次调用此方法即可
                .body(str)//表单内容
                .timeout(20000)//超时，毫秒
                .execute().body();
        log.info("添加coder workspase返回：{}", result2);
        return JSONObject.parseObject(result2).getString("id");
        // 启动
//        changeStatusWorkspace(JSONObject.parseObject(result2).getString("id"), "start");
        // {"id":"2d212fa7-98cb-4911-8490-e019b9c36c9d","created_at":"2024-12-11T16:20:42.983658Z","updated_at":"2024-12-11T16:20:42.983658Z","owner_id":"d15ed23a-f02a-413f-9640-d1d0e6e514fc","owner_name":"zxnapi1212","owner_avatar_url":"","organization_id":"66e8a45c-fdab-4118-99eb-ace95a7a2be0","organization_name":"coder","template_id":"9057d664-5e35-4ad0-ac77-1cfd78cf12f1","template_name":"kubernetes","template_display_name":"Kubernetes","template_icon":"/icon/k8s.png","template_allow_user_cancel_workspace_jobs":false,"template_active_version_id":"d3563a10-0bbe-4bce-b037-28cc9989ca71","template_require_active_version":false,"latest_build":{"id":"644c6159-0b67-40c6-b9b6-9b8e1b7f01c9","created_at":"2024-12-11T16:20:42.999554Z","updated_at":"2024-12-11T16:20:42.999554Z","workspace_id":"2d212fa7-98cb-4911-8490-e019b9c36c9d","workspace_name":"zxnapi1212","workspace_owner_id":"d15ed23a-f02a-413f-9640-d1d0e6e514fc","workspace_owner_name":"zxnapi1212","workspace_owner_avatar_url":"","template_version_id":"d3563a10-0bbe-4bce-b037-28cc9989ca71","template_version_name":"","build_number":1,"transition":"start","initiator_id":"0e51068e-a6ef-4285-b997-0d7f4f5c0dde","initiator_name":"admin","job":{"id":"0676a098-58ed-46ea-98c8-af0edc006769","created_at":"2024-12-11T16:20:42.999554Z","status":"pending","file_id":"13a71500-5872-4d59-a728-ef23fcbfba71","tags":{"owner":"","scope":"organization"},"queue_position":0,"queue_size":0},"reason":"initiator","resources":[],"deadline":null,"max_deadline":null,"status":"pending","daily_cost":0},"outdated":false,"name":"zxnapi1212","ttl_ms":86400000,"last_used_at":"2024-12-11T16:20:42.983663Z","deleting_at":null,"dormant_at":null,"health":{"healthy":true,"failing_agents":[]},"automatic_updates":"never","allow_renames":false,"favorite":false}
    }

    public static String createWorkspace(CodeWorkspaceDTO codeWorkspaceDTO,String userName,String passno){
        String url = StrUtil.format(ADD_WORKSPACE, codeWorkspaceDTO.getUserId());
        JSONObject top = new JSONObject();
        top.put("name", codeWorkspaceDTO.getName());
        top.put("template_version_id", codeWorkspaceDTO.getTemplateVersionId());
        JSONArray richParameter = new JSONArray();
        JSONObject environment = new JSONObject();
        environment.put("name", "environment");
        environment.put("value", StringUtils.isNotEmpty(codeWorkspaceDTO.getEnvironment()) ? codeWorkspaceDTO.getEnvironment() :"base");
        richParameter.add(environment);

        JSONObject cpu = new JSONObject();
        cpu.put("name", "cpu");
        cpu.put("value", StringUtils.isNotEmpty(codeWorkspaceDTO.getCpu()) ? codeWorkspaceDTO.getCpu() :"2");
        richParameter.add(cpu);

        JSONObject memory = new JSONObject();
        memory.put("name", "memory");
        memory.put("value", StringUtils.isNotEmpty(codeWorkspaceDTO.getMemory()) ? codeWorkspaceDTO.getMemory() :"2");
        richParameter.add(memory);

        JSONObject git_branch = new JSONObject();
        git_branch.put("name", "git_branch");
        git_branch.put("value", StringUtils.isNotEmpty(codeWorkspaceDTO.getGitBranch()) ? codeWorkspaceDTO.getGitBranch() :"main");
        richParameter.add(git_branch);

        JSONObject git_repo = new JSONObject();
        git_repo.put("name", "git_repo");
//        String repo = codeWorkspaceDTO.getGitRepo().replace("https://",
//                "https://"+userName+":"+passno+"@");
        git_repo.put("value", codeWorkspaceDTO.getGitRepo());
        richParameter.add(git_repo);

        JSONObject git_username = new JSONObject();
        git_username.put("name", "git_username");
        if (StringUtils.isNotEmpty(codeWorkspaceDTO.getUserName())) {
            git_username.put("value", codeWorkspaceDTO.getUserName());
        } else {
            git_username.put("value", userName);
        }
        richParameter.add(git_username);


        JSONObject enable_code_server = new JSONObject();
        enable_code_server.put("name", "enable_code_server");
        enable_code_server.put("value", StringUtils.isNotEmpty(codeWorkspaceDTO.getEnableCodeServer()) ? codeWorkspaceDTO.getEnableCodeServer() :"true");
        richParameter.add(enable_code_server);

        JSONObject enable_filebrowser = new JSONObject();
        enable_filebrowser.put("name", "enable_filebrowser");
        enable_filebrowser.put("value", StringUtils.isNotEmpty(codeWorkspaceDTO.getEnableFilebrowser()) ? codeWorkspaceDTO.getEnableFilebrowser() :"false");
        richParameter.add(enable_filebrowser);

        JSONObject enable_kasmvnc = new JSONObject();
        enable_kasmvnc.put("name", "enable_kasmvnc");
        enable_kasmvnc.put("value", StringUtils.isNotEmpty(codeWorkspaceDTO.getEnableKasmvnc()) ? codeWorkspaceDTO.getEnableKasmvnc() :"false");
        richParameter.add(enable_kasmvnc);

        JSONObject enable_terminal = new JSONObject();
        enable_terminal.put("name", "enable_terminal");
        enable_terminal.put("value", StringUtils.isNotEmpty(codeWorkspaceDTO.getEnableTerminal()) ? codeWorkspaceDTO.getEnableTerminal() :"true");
        richParameter.add(enable_terminal);

        JSONObject enable_vscode_desktop = new JSONObject();
        enable_vscode_desktop.put("name", "enable_vscode_desktop");
        enable_vscode_desktop.put("value", StringUtils.isNotEmpty(codeWorkspaceDTO.getEnableVscodeDesktop()) ? codeWorkspaceDTO.getEnableVscodeDesktop() :"true");
        richParameter.add(enable_vscode_desktop);
        top.put("rich_parameter_values", richParameter);

        top.put("rich_parameter_values", richParameter);
           //链式构建请求
        String result2 = HttpRequest.post(url)
                .header("Coder-Session-Token", "FPcA7S0rcH-Xy1yBG9LaY7zMPdj8IB6da")//头信息，多个头信息多次调用此方法即可
                .body(top.toString())//表单内容
                .timeout(20000)//超时，毫秒
                .execute().body();
        log.info("添加coder workspase返回：{}", result2);
        return JSONObject.parseObject(result2).getString("id");
    }

    /**
     * 启动停止
     * @param workpaceId
     * @param status
     */
    public static String changeStatusWorkspace(String workpaceId,String status){
        String url = StrUtil.format(START_WORKSPACE, workpaceId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("transition",status);
        //链式构建请求
        String result2 = HttpRequest.post(url)
                .header("Coder-Session-Token", "FPcA7S0rcH-Xy1yBG9LaY7zMPdj8IB6da")//头信息，多个头信息多次调用此方法即可
                .body(jsonObject.toJSONString())//表单内容
                .timeout(20000)//超时，毫秒
                .execute().body();
        log.info("coder workspase status 返回：{}", result2);
        return result2;
    }


    /**
     * 删除
     * @param workpaceId
     */
    public static String deleteWorkspace(String workpaceId){
        String url = StrUtil.format(START_WORKSPACE, workpaceId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("transition", "delete");
        jsonObject.put("orphan", false);

        //链式构建请求
        String result2 = HttpRequest.post(url)
                .header("Coder-Session-Token", "FPcA7S0rcH-Xy1yBG9LaY7zMPdj8IB6da")//头信息，多个头信息多次调用此方法即可
                .body(jsonObject.toJSONString())//表单内容
                .timeout(20000)//超时，毫秒
                .execute().body();
        log.info("coder workspase 删除 返回：{}", result2);
        return result2;
    }

    /**
     * 获取状态
     * @param workpaceName
     * @param userId
     */
    public static String getStatusWorkspace(String workpaceName,String userId){
        String url = StrUtil.format(STATUS_WORKSPACE, userId,workpaceName);
        //链式构建请求
        String result2 = HttpRequest.get(url)
                .header("Coder-Session-Token", "FPcA7S0rcH-Xy1yBG9LaY7zMPdj8IB6da")//头信息，多个头信息多次调用此方法即可
                .timeout(20000)//超时，毫秒
                .execute().body();
        log.info("coder workspase status 返回：{}", result2);
        JSONObject jsonObject = JSONObject.parseObject(result2);
        if (Objects.nonNull(jsonObject.getJSONObject("latest_build"))) {
            String status = jsonObject.getJSONObject("latest_build").getString("status");
            return status;
        } else {
            throw new UtilException(jsonObject.getString("message"));
        }
    }


    public static String login(String email,String password){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("email", email);
        jsonObject.put("password", password);
        //链式构建请求
        String result2 = HttpRequest.post(LOGIN)
                .header("Coder-Session-Token", "FPcA7S0rcH-Xy1yBG9LaY7zMPdj8IB6da")//头信息，多个头信息多次调用此方法即可
                .body(jsonObject.toJSONString())//表单内容
                .timeout(20000)//超时，毫秒
                .execute().body();
        log.info("登录token：{}",result2);
        return result2;
    }

    public static void main(String[] args) {
        System.out.println( addUser("zxnapi12221750","yanchan0424","zxnapi121801@example.com"));
    }

}
